import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/comic_chapter_model.dart';
import '../utils/http_helper.dart';

// 漫画阅读器状态
class ComicReaderState {
  final ComicChapterModel? currentChapter;
  final List<String> imageUrls;
  final List<ChapterImageInfo> allImages;
  final int currentImageIndex;
  final bool isLoading;
  final String? error;
  final bool showUI;
  final bool isDarkMode;
  final Map<String, ComicChapterModel> chapterCache;
  final List<String> chapterIds;

  ComicReaderState({
    this.currentChapter,
    this.imageUrls = const [],
    this.allImages = const [],
    this.currentImageIndex = 0,
    this.isLoading = false,
    this.error,
    this.showUI = true,
    this.isDarkMode = false,
    this.chapterCache = const {},
    this.chapterIds = const [],
  });

  ComicReaderState copyWith({
    ComicChapterModel? currentChapter,
    List<String>? imageUrls,
    List<ChapterImageInfo>? allImages,
    int? currentImageIndex,
    bool? isLoading,
    String? error,
    bool? showUI,
    bool? isDarkMode,
    Map<String, ComicChapterModel>? chapterCache,
    List<String>? chapterIds,
  }) {
    return ComicReaderState(
      currentChapter: currentChapter ?? this.currentChapter,
      imageUrls: imageUrls ?? this.imageUrls,
      allImages: allImages ?? this.allImages,
      currentImageIndex: currentImageIndex ?? this.currentImageIndex,
      isLoading: isLoading ?? this.isLoading,
      error: error,
      showUI: showUI ?? this.showUI,
      isDarkMode: isDarkMode ?? this.isDarkMode,
      chapterCache: chapterCache ?? this.chapterCache,
      chapterIds: chapterIds ?? this.chapterIds,
    );
  }
}

// 新增：章节图片信息类
class ChapterImageInfo {
  final String imageUrl;
  final String chapterId;
  final String chapterTitle;
  final int imageIndex; // 在该章节中的索引
  final int globalIndex; // 在全局数组中的索引

  ChapterImageInfo({
    required this.imageUrl,
    required this.chapterId,
    required this.chapterTitle,
    required this.imageIndex,
    required this.globalIndex,
  });
}

// 漫画阅读器状态管理
class ComicReaderNotifier extends StateNotifier<ComicReaderState> {
  ComicReaderNotifier() : super(ComicReaderState());

  // 初始化阅读器，加载当前章节及相邻章节
  Future<void> initializeReader(
      String currentChapterId, List<String> chapterIds) async {
    state = state.copyWith(
      chapterIds: chapterIds,
      isLoading: true,
      error: null,
    );

    final currentIndex = chapterIds.indexOf(currentChapterId);
    if (currentIndex == -1) return;

    // 确定要加载的章节范围（当前章节前后各1-2章）
    final startIndex = (currentIndex - 1).clamp(0, chapterIds.length - 1);
    final endIndex = (currentIndex + 2).clamp(0, chapterIds.length - 1);

    final chaptersToLoad = chapterIds.sublist(startIndex, endIndex + 1);

    // 并行加载多个章节
    await _loadMultipleChapters(chaptersToLoad, currentChapterId);
  }

  // 批量加载章节
  Future<void> _loadMultipleChapters(
      List<String> chapterIds, String currentChapterId) async {
    final futures =
        chapterIds.map((chapterId) => _loadSingleChapter(chapterId));
    await Future.wait(futures);

    // 重新构建全局图片数组
    _rebuildAllImages(currentChapterId);
  }

  // 加载单个章节（不更新UI状态）
  Future<ComicChapterModel?> _loadSingleChapter(String chapterId) async {
    if (state.chapterCache.containsKey(chapterId)) {
      return state.chapterCache[chapterId];
    }

    try {
      final response = await HttpUtil().getModel<ComicChapterModel>(
        'Comic/GetComicChapter',
        params: {'chapterId': chapterId},
        fromJson: (json) =>
            ComicChapterModel.fromJson(json as Map<String, dynamic>),
      );
      if (response?.status == 200 && response?.result != null) {
        final chapter = response!.result!;
        final newCache =
            Map<String, ComicChapterModel>.from(state.chapterCache);
        newCache[chapterId] = chapter;
        state = state.copyWith(chapterCache: newCache);
        return chapter;
      }
    } catch (e) {
      print('加载章节失败: $chapterId, $e');
    }
    return null;
  }

  // 重新构建全局图片数组
  void _rebuildAllImages(String currentChapterId) {
    final allImages = <ChapterImageInfo>[];
    int globalIndex = 0;
    int currentImageIndex = 0;

    // 按章节顺序构建图片数组
    for (final chapterId in state.chapterIds) {
      final chapter = state.chapterCache[chapterId];
      if (chapter != null) {
        for (int i = 0; i < chapter.imageUrls.length; i++) {
          final imageInfo = ChapterImageInfo(
            imageUrl: chapter.imageUrls[i],
            chapterId: chapterId,
            chapterTitle: chapter.title ?? 'Chapter',
            imageIndex: i,
            globalIndex: globalIndex,
          );

          allImages.add(imageInfo);

          // 记录当前章节第一张图片的位置
          if (chapterId == currentChapterId && i == 0) {
            currentImageIndex = globalIndex;
          }

          globalIndex++;
        }
      }
    }

    state = state.copyWith(
      allImages: allImages,
      currentImageIndex: currentImageIndex,
      isLoading: false,
    );
  }

  // 动态加载更多章节（当用户接近边界时）
  Future<void> loadMoreChapters(bool isNext) async {
    if (state.chapterIds.isEmpty) return;

    final currentChapterIds = state.chapterCache.keys.toList();
    final allChapterIds = state.chapterIds;

    if (isNext) {
      // 加载后续章节
      final lastLoadedIndex = allChapterIds.indexOf(currentChapterIds.last);
      if (lastLoadedIndex < allChapterIds.length - 1) {
        final nextChapterIds = allChapterIds.sublist(lastLoadedIndex + 1,
            (lastLoadedIndex + 3).clamp(0, allChapterIds.length));
        await _loadMultipleChapters(
            nextChapterIds,
            state.allImages.isNotEmpty
                ? state.allImages[state.currentImageIndex].chapterId
                : '');
      }
    } else {
      // 加载前面的章节
      final firstLoadedIndex = allChapterIds.indexOf(currentChapterIds.first);
      if (firstLoadedIndex > 0) {
        final prevChapterIds = allChapterIds.sublist(
            (firstLoadedIndex - 2).clamp(0, allChapterIds.length),
            firstLoadedIndex);
        await _loadMultipleChapters(
            prevChapterIds,
            state.allImages.isNotEmpty
                ? state.allImages[state.currentImageIndex].chapterId
                : '');
      }
    }
  }

  // 更新当前图片索引，并检查是否需要加载更多章节
  void updateImageIndex(int index) {
    state = state.copyWith(currentImageIndex: index);

    // 检查是否需要预加载更多章节
    final totalImages = state.allImages.length;
    if (index > totalImages * 0.8) {
      loadMoreChapters(true); // 加载后续章节
    } else if (index < totalImages * 0.2) {
      loadMoreChapters(false); // 加载前面章节
    }
  }

  // 获取当前章节信息
  ChapterImageInfo? getCurrentImageInfo() {
    if (state.currentImageIndex < state.allImages.length) {
      return state.allImages[state.currentImageIndex];
    }
    return null;
  }

  // 加载章节数据
  Future<void> loadChapter(String chapterId) async {
    // 先检查缓存
    if (state.chapterCache.containsKey(chapterId)) {
      final cachedChapter = state.chapterCache[chapterId]!;
      state = state.copyWith(
        currentChapter: cachedChapter,
        imageUrls: cachedChapter.imageUrls,
        currentImageIndex: 0,
        isLoading: false,
        error: null,
      );
      return;
    }

    state = state.copyWith(isLoading: true, error: null);

    try {
      final response = await HttpUtil().getModel<ComicChapterModel>(
        'Comic/GetComicChapter',
        params: {'chapterId': chapterId},
        fromJson: (json) =>
            ComicChapterModel.fromJson(json as Map<String, dynamic>),
      );

      if (response?.status == 200 && response?.result != null) {
        final chapter = response!.result!;
        final newCache =
            Map<String, ComicChapterModel>.from(state.chapterCache);
        newCache[chapterId] = chapter;

        state = state.copyWith(
          currentChapter: chapter,
          imageUrls: chapter.imageUrls,
          currentImageIndex: 0,
          isLoading: false,
          chapterCache: newCache,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: response?.message ?? 'Failed to load chapter',
        );
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Network error: $e',
      );
    }
  }

  // 预加载下一章节
  Future<void> preloadNextChapter(String nextChapterId) async {
    if (state.chapterCache.containsKey(nextChapterId)) return;

    try {
      final response = await HttpUtil().getModel<ComicChapterModel>(
        'Comic/GetComicChapter',
        params: {'chapterId': nextChapterId},
        fromJson: (json) =>
            ComicChapterModel.fromJson(json as Map<String, dynamic>),
      );

      if (response?.status == 200 && response?.result != null) {
        final chapter = response!.result!;
        final newCache =
            Map<String, ComicChapterModel>.from(state.chapterCache);
        newCache[nextChapterId] = chapter;
        state = state.copyWith(chapterCache: newCache);
      }
    } catch (e) {
      print('预加载章节失败: $e');
    }
  }

  // 切换到下一章节（在当前页面无缝浏览）
  Future<void> switchToNextChapter(String nextChapterId) async {
    // 如果下一章节已经在缓存中，直接切换
    if (state.chapterCache.containsKey(nextChapterId)) {
      final nextChapter = state.chapterCache[nextChapterId]!;
      state = state.copyWith(
        currentChapter: nextChapter,
        imageUrls: nextChapter.imageUrls,
        currentImageIndex: 0, // 重置到第一张图片
        error: null,
      );
      return;
    }

    // 如果没有缓存，则加载章节数据
    state = state.copyWith(isLoading: true, error: null);

    try {
      final response = await HttpUtil().getModel<ComicChapterModel>(
        'Comic/GetComicChapter',
        params: {'chapterId': nextChapterId},
        fromJson: (json) =>
            ComicChapterModel.fromJson(json as Map<String, dynamic>),
      );

      if (response?.status == 200 && response?.result != null) {
        final chapter = response!.result!;
        final newCache =
            Map<String, ComicChapterModel>.from(state.chapterCache);
        newCache[nextChapterId] = chapter;

        state = state.copyWith(
          currentChapter: chapter,
          imageUrls: chapter.imageUrls,
          currentImageIndex: 0, // 重置到第一张图片
          isLoading: false,
          chapterCache: newCache,
          error: null,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: response?.message ?? '加载下一章节失败',
        );
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: '网络错误: $e',
      );
    }
  }

  // 切换到上一章节（在当前页面无缝浏览）
  Future<void> switchToPreviousChapter(String previousChapterId) async {
    // 如果上一章节已经在缓存中，直接切换
    if (state.chapterCache.containsKey(previousChapterId)) {
      final previousChapter = state.chapterCache[previousChapterId]!;
      state = state.copyWith(
        currentChapter: previousChapter,
        imageUrls: previousChapter.imageUrls,
        currentImageIndex: previousChapter.imageUrls.length - 1, // 跳转到最后一张图片
        error: null,
      );
      return;
    }

    // 如果没有缓存，则加载章节数据
    state = state.copyWith(isLoading: true, error: null);

    try {
      final response = await HttpUtil().getModel<ComicChapterModel>(
        'Comic/GetComicChapter',
        params: {'chapterId': previousChapterId},
        fromJson: (json) =>
            ComicChapterModel.fromJson(json as Map<String, dynamic>),
      );

      if (response?.status == 200 && response?.result != null) {
        final chapter = response!.result!;
        final newCache =
            Map<String, ComicChapterModel>.from(state.chapterCache);
        newCache[previousChapterId] = chapter;

        state = state.copyWith(
          currentChapter: chapter,
          imageUrls: chapter.imageUrls,
          currentImageIndex: chapter.imageUrls.length - 1, // 跳转到最后一张图片
          isLoading: false,
          chapterCache: newCache,
          error: null,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: response?.message ?? '加载上一章节失败',
        );
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: '网络错误: $e',
      );
    }
  }

  // 切换UI显示状态
  void toggleUI() {
    state = state.copyWith(showUI: !state.showUI);
  }

  // 切换夜间模式
  void toggleDarkMode() {
    state = state.copyWith(isDarkMode: !state.isDarkMode);
  }

  // 清除错误
  void clearError() {
    state = state.copyWith(error: null);
  }
}

// Provider
final comicReaderProvider =
    StateNotifierProvider<ComicReaderNotifier, ComicReaderState>(
  (ref) => ComicReaderNotifier(),
);
